package com.bigstar.lolen_e;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class ChampionGallery extends Activity  implements OnItemSelectedListener{
	private Gallery gallery;
	String champName;
	int size;
	int csize;
	private Handler hHandler;
	ImageView iv[];
	AddImageAdpapter adpapter;
	Bitmap bmlist[];
	int wallpaperindex;
	private ArrayList<SkinData> arrSkin;
	private boolean dialog = false;
	private int champid;
    @Override
    protected void onResume() {
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
    	super.onResume();
    }
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.champ_gallery);
		AdView adview = (AdView) findViewById(R.id.adView);
		AdRequest re = new AdRequest();
		adview.loadAd(re);
		arrSkin = new ArrayList<SkinData>();
		arrSkin.clear();
		if(getIntent().getStringExtra("champ_id") != null){
			champid = Integer.parseInt(getIntent().getStringExtra("champ_id"));	
		}
		champName = ChampionData.champions.get(champid).name_en;
		WaitCloseReg();
		AssetManager assetManager = this.getResources().getAssets();
		AssetInputStream ais = null;
		try {
			ais = (AssetInputStream) assetManager.open("gallery/"+ champName + ".txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(ais));
			String line;
			while ((line = br.readLine()) != null) {
	            StringTokenizer st = new StringTokenizer(line, ";");
	        	SkinData skin = new SkinData();
	        	skin.name_en = st.nextToken();
	        	skin.name_kor = st.nextToken();
	        	skin.price = st.nextToken();
	        	skin.illust = st.nextToken();
	        	skin.skin = st.nextToken();
	        	skin.illust_ch = st.nextToken();
	        	arrSkin.add(skin);
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		csize = 0;
		size = arrSkin.size();
		iv = new ImageView[size];
		bmlist = new Bitmap[size];
		int w = this.getWindowManager().getDefaultDisplay().getWidth();
		int wratio = (int) (w/1.6);
		
		for (int i = 0; i < size; i++) {
			iv[i] = new ImageView(this);
			iv[i].setImageResource(R.drawable.loading);
			iv[i].setLayoutParams(new Gallery.LayoutParams(w, wratio));
			iv[i].setScaleType(ImageView.ScaleType.FIT_XY);
		}
		gallery = (Gallery) findViewById(R.id.gallery01);
		gallery.setSpacing(30);
		adpapter = new AddImageAdpapter(ChampionGallery.this);
		final GalleryNavigator navi = (GalleryNavigator) findViewById(R.id.navi);
		navi.setSize(size);
		gallery.setAdapter(adpapter);
		gallery.setOnItemSelectedListener(new OnItemSelectedListener(){


			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				wallpaperindex = position;
				TextView tv = (TextView) findViewById(R.id.name_en);
				tv.setText(arrSkin.get(position).name_en);
				tv = (TextView) findViewById(R.id.name_kor);
				tv.setText(arrSkin.get(position).name_kor);
				tv = (TextView) findViewById(R.id.price);
				tv.setText(arrSkin.get(position).price);
				navi.setPosition(position);
				navi.invalidate();
			}


			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
			
		});
		TextView tv = (TextView) findViewById(R.id.name_en);
		tv.setText(arrSkin.get(0).name_en);
		tv = (TextView) findViewById(R.id.name_kor);
		tv.setText(arrSkin.get(0).name_kor);
		tv.setVisibility(View.GONE);
		tv = (TextView) findViewById(R.id.price);
		tv.setText(arrSkin.get(0).price);
		gallery.setSelection(0);
		navi.setPosition(0);
		navi.invalidate();
		Thread t = new Thread(mUpdateResults);
		t.start();
	}

	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			boolean image_save = pref.getBoolean("image_save", true);
			boolean illust_us = pref.getBoolean("illust_us", true);
			if (csize < size) {
				Bitmap bm;
				if(illust_us){
					if ((bm = Utils.loadBitmap(ChampionGallery.this, "illust", champName+"_"+csize+".jpg")) != null) {
						bmlist[csize] = bm;
					} else if ((bm = Utils.getBitmapFromUrl(arrSkin.get(csize).illust)) != null) {
						bmlist[csize] = bm;
						Utils.saveBitmap(ChampionGallery.this, bm, "illust", champName+"_"+csize+".jpg", image_save);
					}
				}else{
					if (arrSkin.get(csize).illust_ch.equals("x")) {
						if ((bm = Utils.loadBitmap(ChampionGallery.this, "illust", champName+"_"+csize+".jpg")) != null) {
							bmlist[csize] = bm;
						} else if ((bm = Utils.getBitmapFromUrl(arrSkin.get(csize).illust)) != null) {
							bmlist[csize] = bm;
							Utils.saveBitmap(ChampionGallery.this, bm, "illust", champName+"_"+csize+".jpg", image_save);
						}
					}else if ((bm = Utils.loadBitmap(ChampionGallery.this, "illust", champName+"_Ch_"+csize+".jpg")) != null) {
						bmlist[csize] = bm;
					} else if ((bm = Utils.getBitmapFromUrl(arrSkin.get(csize).illust_ch)) != null) {
						bmlist[csize] = bm;
						Utils.saveBitmap(ChampionGallery.this, bm, "illust", champName+"_Ch_"+csize+".jpg", image_save);
					}	
				}
				csize++;
				Message msg = Message.obtain();
				msg.obj = "run";
				System.gc();
				hHandler.sendMessageDelayed(msg, 100);
				Thread t = new Thread(this);
				t.start();
			}
		}

	};

	private void WaitCloseReg() {
		hHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				adpapter.notifyDataSetChanged();
			}
		};
	}

	public class AddImageAdpapter extends BaseAdapter {
		private Context context;

		int galleryBackground;

		public AddImageAdpapter(Context c) {
			context = c;

			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery01);
			galleryBackground =

			ta.getResourceId(
					R.styleable.Gallery01_android_galleryItemBackground, 0);
			ta.recycle();
		}

		public int getCount() {
			return size;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (bmlist[position] == null) {
				iv[position].setImageResource(R.drawable.loading);
			} else {
				iv[position].setImageBitmap(bmlist[position]);
			}
			return iv[position];
		}

	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, 0, 0, "Zoom"); 
		menu.add(Menu.NONE, 1, 1, "View Skin"); 
		menu.add(Menu.NONE, 2, 2, "Select Wallpaper"); 
		return result;   
	}  
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){ 
		case 0:
			if(bmlist[wallpaperindex] != null){
				Utils.skin = bmlist[wallpaperindex];
        		Intent intent = new Intent(ChampionGallery.this, Skin.class);
        		startActivity(intent);	
			}
			break;
		case 1:
			if(dialog){
				return true;
			}
			dialog = true;
			Utils.skin = null;
			if((Utils.skin = Utils.loadBitmap(ChampionGallery.this, "skin", champName+"_"+wallpaperindex+".jpg")) == null){
				Utils.skin = Utils.getBitmapFromUrl(arrSkin.get(wallpaperindex).skin);	
				SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
				boolean image_save = pref.getBoolean("image_save", true);
				Utils.saveBitmap(ChampionGallery.this, Utils.skin, "skin", champName+"_"+wallpaperindex+".jpg", image_save);
			}
			if(Utils.skin == null){
				return ( super.onOptionsItemSelected(item)); 
			}
			ImageView iv = new ImageView(ChampionGallery.this);
			iv.setImageBitmap(Utils.skin);
			iv.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
	        		Intent intent = new Intent(ChampionGallery.this, Skin.class);
	        		startActivity(intent);
				}
			});
			new AlertDialog.Builder(ChampionGallery.this)
			.setTitle("In Game ScreenShot")
			.setView(iv)
			.setPositiveButton("image for a larger", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = new Intent(ChampionGallery.this, Skin.class);
	        		startActivity(intent);
				}
			})
			.setNegativeButton("Close", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			})
			.create().show();
			dialog = false;
			break;
		case 2:
			if (bmlist[wallpaperindex] != null) {
				new AlertDialog.Builder(ChampionGallery.this)
    			.setTitle("Would you like to make it as wallpaper?")
				.setPositiveButton("yes",
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						final WallpaperManager wm = WallpaperManager.getInstance(ChampionGallery.this);
						try {
							wm.setBitmap(bmlist[wallpaperindex]);
							Toast.makeText(getApplicationContext(),"Complete",Toast.LENGTH_SHORT).show();
						} catch (IOException e) {
							Toast.makeText(getApplicationContext(),"fail",Toast.LENGTH_SHORT).show();
							e.printStackTrace();
						}
					}
				})
				.setNegativeButton("no",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int whichButton) {
					}
				}).create().show();
			}
			break;
		}
		return ( super.onOptionsItemSelected(item)); 
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		for(int i = 0; i < bmlist.length; i++){
			if(bmlist[i] != null){
				bmlist[i].recycle();
				bmlist[i] = null;
			}
			System.gc();
		}
	}
   

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	
	class SkinData{
		String name_en;
		String name_kor;
		String price;
		String illust;
		String skin;
		String illust_ch;
	}
	
}
